import _thread
#from ImgData import *
from machine import Pin
import neopixel
import network
import utime
import time
from neopixel import NeoPixel
from machine import Pin
from 驱动.ws2812Screen import WS2812Screen
import ujson
import 驱动.new_requests as urequests

wifi_name = 'frank'  # wifi名称
password = '0092009200920092'  # wifi密码

UID = 14368720  # B站UID，在个人主页有显示
bv_id = "1bG4y197Lq"  # 视频BV号(放在引号在，字符串格式)，在视频的网址中，BV后边的内容，例video/BV1bG4y197Lq/?spm_id_from中的1bG4y197Lq

#led = Pin(9, Pin.OUT)

#led.value(1)

# 初始化WiFi连接
def connect_wifi():
    wifi_times = 0
    wlan = network.WLAN(network.STA_IF)  # 创建STA模式
    wlan.active(False)  # 激活wifi
    wlan.active(True)  # 激活wifi
    wlan.scan()
    
    if not wlan.isconnected():  # 首次判断状态，尝试连接
        print('网络连接中...')
        wlan.connect(wifi_name, password)  # 连接wifi

        while not wlan.isconnected():  # 用循环等待wifi连接（wifi连接需要点时间），每1s重新判断一次，若连接成功则不进入循环了
            wifi_times += 1  # 计数器+1
            utime.sleep(1)  # 每次等待1S
            print(wifi_times)
            if wifi_times == 30:  # 如果过了20S都没连上，判定连接失败
                wlan.active(False)
                return False  # 返回False

    print("wifi连接成功！")  # 若连接成功则不进入循环，从这里向下继续
    print('network connect', wlan.status())  # 返回网络工作状态,可能是信号强度
    r = urequests.get(f'http://api.bilibili.com/x/relation/stat?vmid={UID}')
    p = ujson.loads(r.text)
    fans = p['data']['follower']
    print(fans)
    r1 = urequests.get('https://api.bilibili.com/x/web-interface/archive/related?bvid=' + bv_id)
    p1 = ujson.loads(r1.text)
    print(p1)
    likes = p1['data']['stat']['like']
    coins = p1['data']['stat']['coin']
    stars = p1['data']['stat']['favorite']

    r2 = urequests.get('http://web.juhe.cn:8080/finance/stock/hs?gid=&type=0&key=9410eb82400dde354c6023a37eafd0e2')
    p2 = ujson.loads(r2.text)
    now_stock = round(float(p2['result']['nowpri']), 2)  # float将字符串转为浮点数，round四舍五入保留两位小数
    yes_stock = round(float(p2['result']['yesPri']), 2)

    print(f"粉丝为：{fans}")
    print(f"点赞为：{likes}")
    print(f"硬币为：{coins}")
    print(f"收藏为: {stars}")
    print(f"上证指数为：{now_stock}")
    print(f"昨日上证指数为：{yes_stock}")
    return True

# WS2812B任务
def ws2812b_task():


    SCREEN_WIDTH = 32  # 屏幕宽
    SCREEN_HEIGHT = 8  # 屏幕高

    num_leds = SCREEN_WIDTH * SCREEN_HEIGHT  # 像素数量(led灯珠数量)

    np = NeoPixel(Pin(5), num_leds + 64)  # 创建像素序列对象

    screen = WS2812Screen(np, SCREEN_WIDTH, SCREEN_HEIGHT)  # 创建屏幕对象

#     流水灯动画
    for i in range(8):
        for j in range(32):
            screen.draw_pixel(j, i, (50, 10 + j * 5, 10 + i * 10), 0.5)
            screen.show()


# 在核心0上运行WiFi连接任务
_thread.start_new_thread(connect_wifi, ())

# 在核心1上运行WS2812B任务
_thread.start_new_thread(ws2812b_task, ())

# 主循环
# while True:
#     pass
#connect_wifi()